﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.IO;
using System.Collections.ObjectModel;
using System.Data.Objects.DataClasses;
using System.Data;
using System.Data.Objects;
using System.Windows.Data;
using DocumentManagement.Models;
using Microsoft.Win32;


namespace DocumentManagement.ViewsModels
{
    
   public class AddDocumentInViewsModel : ViewsModelBase
    {
  
        private QSHCEntities1 _entityModels;
        public QSHCEntities1 EntityModels
        {
            get { return _entityModels; }
            set
            {
                if (_entityModels != value)
                {
                    _entityModels = value;
                    OnPropertyChanged("EntityModels");
                }
            }
        }

        private Receive _myReceive; 
        public Receive MyReceive
        {
            get { return _myReceive; }
            set
            {
                if (_myReceive != value)
                {
                    _myReceive = value;
                    OnPropertyChanged("MyReceive");

                    if(MyReceive != null)
                        AttachICV = CollectionViewSource.GetDefaultView(MyReceive.ReceiveAttachedFiles.Where(p => p.Active == true));
                }
            }
        }

      
 
        private ReceiveAttachedFile _selectedAttachFile;
        public ReceiveAttachedFile SelectedAttachFile
        {
            get { return _selectedAttachFile; }
            set
            {
                if (_selectedAttachFile != value)
                {
                    _selectedAttachFile = value;
                    OnPropertyChanged("SelectedAttachFile");
                }
            }
        }

        private bool _myAction1;
        public bool MyAction1
        {
            get { return _myAction1; }
            set
            {
                if (_myAction1 != value)
                {
                    _myAction1 = value;
                    OnPropertyChanged("MyAction1");
                }
            }
        }
        private bool _myAction2;
        public bool MyAction2
        {
            get { return _myAction2; }
            set
            {
                if (_myAction2 != value)
                {
                    _myAction2 = value;
                    OnPropertyChanged("MyAction2");
                }
            }
        }

        private bool _myspeed1;
        public bool MySpeed1
        {
            get { return _myspeed1; }
            set
            {
                if (_myspeed1 != value)
                {
                    _myspeed1 = value;
                    OnPropertyChanged("MySpeed1");
                }
            }
        }
        private bool _myspeed2;
        public bool MySpeed2
        {
            get { return _myspeed2; }
            set
            {
                if (_myspeed2 != value)
                {
                    _myspeed2 = value;
                    OnPropertyChanged("MySpeed2");
                }
            }
        }
        private bool _myspeed3;
        public bool MySpeed3
        {
            get { return _myspeed3; }
            set
            {
                if (_myspeed3 != value)
                {
                    _myspeed3 = value;
                    OnPropertyChanged("MySpeed3");
                }
            }
        }
        private bool _myspeed4;
        public bool MySpeed4
        {
            get { return _myspeed4; }
            set
            {
                if (_myspeed4 != value)
                {
                    _myspeed4 = value;
                    OnPropertyChanged("MySpeed4");
                }
            }
        }
        private bool _myStatusDoc1;
        public bool MyStatusDoc1
        {
            get { return _myStatusDoc1; }
            set
            {
                if (_myStatusDoc1 != value)
                {
                    _myStatusDoc1 = value;
                    OnPropertyChanged("MyStatusDoc1");
                }
            }
        }
        private bool _myStatusDoc2;
        public bool MyStatusDoc2
        {
            get { return _myStatusDoc2; }
            set
            {
                if (_myStatusDoc2 != value)
                {
                    _myStatusDoc2 = value;
                    OnPropertyChanged("MyStatusDoc2");
                }
            }
        }

       
 
        private ICollectionView _attachICV;
        public ICollectionView AttachICV
        {
            get { return _attachICV; }
            set
            {
                if (_attachICV != value)
                {
                    _attachICV = value;
                    OnPropertyChanged("AttachICV");
                }
            }
        }

        public AddDocumentInViewsModel()
        {
           
        }
       

        public void GetBrowse()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.DefaultExt = ".txt";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                // Open document
                var filename = (MyReceive.ReceiveDate.Year + 543).ToString("D4") + MyReceive.ReceiveDate.Month.ToString("D2") + MyReceive.ReceiveDate.Day.ToString("D2") + "_" + dlg.SafeFileName;

                //TxtPath = dlg.FileName;

                var AddToDataGrid = new ReceiveAttachedFile { FileName = filename, FilePath = dlg.FileName, Active = true};
                MyReceive.ReceiveAttachedFiles.Add(AddToDataGrid);

                AttachICV.Refresh();
  
            }
        }
      

        public void SaveToDatabase()
        {
            //if (AttachICV.IsEmpty)
            //{
            //    MessageBox.Show("กรุณาแนนบไฟล์เอกสาร", "กรอกข้อมูลไม่ครบ", MessageBoxButton.OK);
            //    return;
            //}
            //ชั้นความเร็ว
            if (MySpeed1 == true) MyReceive.Speed = 1;
            else if (MySpeed2 == true) MyReceive.Speed = 2;
            else if (MySpeed3 == true) MyReceive.Speed = 3;
            else if (MySpeed4 == true) MyReceive.Speed = 4;

            //การปฏิบัติ
            if (MyAction1 == true) MyReceive.Action = 1;
            else MyReceive.Action = 2;

            if (MyStatusDoc1 == true) MyReceive.Type = 1;
            else MyReceive.Type = 2;
            // Check MyReceive EntityState
            if (MyReceive.EntityState == EntityState.Added || MyReceive.EntityState == EntityState.Detached) //detached ดึงข้อมูลมาจากดาต้าเบสแล้วมีการแก้ไข
            {
                MyReceive.LogData = CreateLogData(LogAction.Create, MyReceive.ReceiveID);
                MyReceive.Active = true;
                EntityModels.Receives.AddObject(MyReceive);
            }
            else if (MyReceive.EntityState == EntityState.Detached)// มีการแก้ไขข้อมูล
            {
               
                MyReceive.LogData = CreateLogData(LogAction.Edit, MyReceive.ReceiveID);
            }

            // Check ReceiveAttachedFiles EntityState
            foreach (var item in MyReceive.ReceiveAttachedFiles)
            {
                if (item.EntityState == EntityState.Added || item.EntityState == EntityState.Detached)
                {
                    File.Copy(item.FilePath, "D:\\uploadReceive\\" + item.FileName, true);
                }
                else if (item.EntityState == EntityState.Modified)
                {
                    if (File.Exists("D:\\uploadReceive\\" + item.FileName))
                    {
                        File.Delete("D:\\uploadReceive\\" + item.FileName);
                    }
                }
            }

            EntityModels.SaveChanges();

            //Clear Data And Autonumber
            MyReceive = new Receive { ReceiveDate = DateTime.Now, DocumentDate = DateTime.Now };
            //GetAutoNumber();
        }

        public void DeleteFile()
        {
            SelectedAttachFile.Active = false;

            if (SelectedAttachFile.EntityState == EntityState.Added || SelectedAttachFile.EntityState == EntityState.Detached)
            {
                MyReceive.ReceiveAttachedFiles.Remove(SelectedAttachFile);
                AttachICV.Refresh();
            }
            else if (SelectedAttachFile.EntityState == EntityState.Modified)
            {
                AttachICV.Refresh();
            }

        }

        

        public void GetAutoNumber()
        {
            string year = Convert.ToString(DateTime.Today.Year + 543);

            try
            {
                string AutoNum = EntityModels.Receives.OrderByDescending(p => p.ReceiveCode).First().ReceiveCode;

                var firstcode = AutoNum.Substring(0, 4);
                var lastcode = Convert.ToInt32(AutoNum.Substring(5, 4));

                if (firstcode != year)
                {
                    MyReceive.ReceiveCode = string.Format("{0}/{1}", year, "0001");
                }
                else
                {
                    MyReceive.ReceiveCode = string.Format("{0}/{1}", year, (lastcode + 1).ToString("D4"));//digital string 4 ตัว เช่น 0003
                }
            }
            catch (Exception ex)
            {
                MyReceive.ReceiveCode = string.Format("{0}/{1}", year, "0001");
            }
            
         
        }
       

        public LogData CreateLogData(LogAction logAction, int primaryKeyID)
        {
            LogData logData = new LogData
            {
                Employee = EntityModels.Employees.Where(p => p.EmployeeCode == CurrentEmployee.EmployeeCode).SingleOrDefault(),
                Action = (byte)logAction,
                LogDateTime = DateTime.Now,
                SchemaName = "BackOffice",
                TableName = "Receives",
                PrimaryKeyID = primaryKeyID,
            };
            return logData;
        }

        public enum LogAction
        {
            Login = 1,
            Logout,
            OpenPage,
            Create,
            Edit,
            Delete,
        }

       //private void OnPropertyChanged(string caller)
       //{
       //    if (PropertyChanged != null)
       //    {
       //        PropertyChanged(this, new PropertyChangedEventArgs(caller));

       //    }
       //}
       // public event PropertyChangedEventHandler PropertyChanged;
    }
}
